import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '跨设备文本传输',
      theme: ThemeData(
          primarySwatch: Colors.blue,
          brightness: Brightness.light,
          visualDensity: VisualDensity.adaptivePlatformDensity,
          fontFamily: 'OPPOSans'),
      home: ChatScreen(),
    );
  }
}

class ChatScreen extends StatefulWidget {
  @override
  _ChatScreenState createState() => _ChatScreenState();
}

class _ChatScreenState extends State<ChatScreen> {
  final TextEditingController _ipController =
      TextEditingController(text: '172.16.61.245');
  final TextEditingController _portController =
      TextEditingController(text: '8080');
  final TextEditingController _messageController = TextEditingController();
  String _localIp = '获取中...';
  List<String> _messages = [];
  ServerSocket? _server;

  @override
  void initState() {
    super.initState();
    _getLocalIp();
    _startServer();
  }

  Future<void> _getLocalIp() async {
    try {
      final interfaces = await NetworkInterface.list();
      for (var interface in interfaces) {
        for (var addr in interface.addresses) {
          if (!addr.isLoopback && addr.type == InternetAddressType.IPv4) {
            setState(() => _localIp = addr.address);
            return;
          }
        }
      }
    } catch (e) {
      print('获取IP失败: $e');
    }
  }

  void _startServer() async {
    try {
      _server = await ServerSocket.bind(InternetAddress.anyIPv4, 8080);
      // 在服务器监听处修改
      _server!.listen((socket) {
        final dataBuffer = <int>[];
        socket.listen(
          (data) {
            dataBuffer.addAll(data);
            try {
              // final message = String.fromCharCodes(dataBuffer);
              final message = utf8.decode(dataBuffer, allowMalformed: false);
              setState(() => _messages.add('接收:\n\r $message'));
              dataBuffer.clear();
            } on FormatException {
              // 数据不完整，等待下次传输
            }
          },
          onError: (e) => print('接收错误: $e'),
          onDone: () => dataBuffer.clear(),
        );
      });
    } catch (e) {
      print('启动服务器失败: $e');
    }
  }

  Future<void> _sendMessage() async {
    final ip = _ipController.text;
    final port = int.tryParse(_portController.text) ?? 8080;
    final message = _messageController.text;

    if (ip.isEmpty || message.isEmpty) return;

    try {
      final socket = await Socket.connect(ip, port);
      socket.write(message);
      // socket.write(utf8.encode(message)); // 明确使用UTF-8编码
      await socket.flush();
      socket.close();
      setState(() {
        _messages.add('发送:\n\r $message');
        _messageController.clear();
      });
    } catch (e) {
      showDialog(
        context: context,
        builder: (ctx) => AlertDialog(
          title: Text('错误'),
          content: Text('无法连接到 $ip:$port'),
          actions: [
            TextButton(onPressed: () => Navigator.pop(ctx), child: Text('确定'))
          ],
        ),
      );
    }
  }

  @override
  void dispose() {
    _server?.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('我的IP: $_localIp')),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            Row(
              children: [
                Expanded(
                  child: TextField(
                    controller: _ipController,
                    decoration: InputDecoration(labelText: '对方IP'),
                  ),
                ),
                SizedBox(width: 10),
                SizedBox(
                  width: 80,
                  child: TextField(
                    controller: _portController,
                    decoration: InputDecoration(labelText: '端口'),
                    keyboardType: TextInputType.number,
                  ),
                ),
              ],
            ),
            SizedBox(height: 20),
            _EnhancedTextField(
              controller: _messageController,
              onSubmitted: _sendMessage,
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: _sendMessage,
              child: Text('发送'),
            ),
            SizedBox(height: 20),
            Expanded(
                child: // 在消息列表项中添加复制功能
                    ListView.builder(
              itemCount: _messages.length,
              itemBuilder: (ctx, i) {
                final message = _messages[i];
                final content =
                    message.replaceFirst(RegExp(r'^(发送|接收):\n\r'), '');

                return GestureDetector(
                  // 新增手势检测
                  onSecondaryTapDown: (details) => _showContextMenu(
                      context, details.globalPosition, content),
                  child: ListTile(
                    title: SelectableText(
                      message,
                      contextMenuBuilder: (context, editableTextState) {
                        // 原生支持
                        return AdaptiveTextSelectionToolbar.buttonItems(
                          anchors: editableTextState.contextMenuAnchors,
                          buttonItems: [
                            ContextMenuButtonItem(
                              label: '复制完整内容',
                              onPressed: () =>
                                  _copyWithFeedback(content, context),
                            ),
                            ...editableTextState
                                .contextMenuButtonItems, // 保留默认选项
                          ],
                        );
                      },
                    ),
                    trailing: IconButton(
                      icon: Icon(Icons.content_copy),
                      onPressed: () => _copyWithFeedback(content, context),
                    ),
                    onLongPress: () => _copyWithFeedback(content, context),
                  ),
                );
              },
            )),
          ],
        ),
      ),
    );
  }

  // 右键菜单显示方法
  void _showContextMenu(BuildContext context, Offset position, String text) {
    final overlay = Overlay.of(context).context.findRenderObject() as RenderBox;

    showMenu(
      context: context,
      position: RelativeRect.fromRect(
        Rect.fromPoints(position, position),
        Offset.zero & overlay.size,
      ),
      items: [
        PopupMenuItem(
          child: Text('复制'),
          onTap: () => _copyWithFeedback(text, context),
        ),
      ],
    );
  }

  // 统一复制方法
  void _copyWithFeedback(String text, BuildContext context) {
    Clipboard.setData(ClipboardData(text: text));
    ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('已复制'), duration: Duration(seconds: 1)));
  }
}

class _EnhancedTextField extends StatefulWidget {
  final TextEditingController controller;
  final VoidCallback onSubmitted;

  const _EnhancedTextField({
    required this.controller,
    required this.onSubmitted,
  });

  @override
  _EnhancedTextFieldState createState() => _EnhancedTextFieldState();
}

class _EnhancedTextFieldState extends State<_EnhancedTextField> {
  final FocusNode _focusNode = FocusNode();
  final _textFieldKey = GlobalKey();

  @override
  void initState() {
    super.initState();
    _focusNode.onKeyEvent = _handleKeyEvent;
  }

  KeyEventResult _handleKeyEvent(FocusNode node, KeyEvent event) {
    if (event is KeyDownEvent) {
      final logicalKey = event.logicalKey;

      // Tab键处理（支持物理键盘）
      if (logicalKey == LogicalKeyboardKey.tab) {
        _insertTextAtCursor('    ');
        return KeyEventResult.handled;
      }

      // Shift+Enter换行（桌面端）
      if (logicalKey == LogicalKeyboardKey.enter) {
        _insertTextAtCursor('\n');
        return KeyEventResult.handled;
      }
    }
    return KeyEventResult.ignored;
  }

  void _insertTextAtCursor(String text) {
    final value = widget.controller.value;
    final start = value.selection.start;
    final end = value.selection.end;

    widget.controller.value = value.copyWith(
      text: value.text.replaceRange(start, end, text),
      selection: TextSelection.collapsed(offset: start + text.length),
    );
  }

  @override
  Widget build(BuildContext context) {
    return TextField(
      key: _textFieldKey,
      focusNode: _focusNode,
      controller: widget.controller,
      maxLines: 10,
      minLines: 1,
      keyboardType: TextInputType.multiline,
      textInputAction: TextInputAction.newline,
      decoration: InputDecoration(
        labelText: '输入消息',
        border: OutlineInputBorder(),
        suffixIcon: IconButton(
          icon: Icon(Icons.keyboard_tab),
          tooltip: '插入缩进（Tab键）',
          onPressed: () => _insertTextAtCursor('    '),
        ),
      ),
      onSubmitted: (_) => widget.onSubmitted(),
    );
  }
}
